package com.czk.gulimall.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czk.common.to.SkuHasStockVo;
import com.czk.common.to.mq.OrderTo;
import com.czk.common.utils.PageUtils;
import com.czk.common.utils.Query;
import com.czk.common.utils.R;
import com.czk.common.vo.MemberResponseVo;
import com.czk.gulimall.order.constant.OrderConstant;
import com.czk.gulimall.order.constant.OrderStatusEnum;
import com.czk.gulimall.order.dao.OrderDao;
import com.czk.gulimall.order.dao.OrderItemDao;
import com.czk.gulimall.order.entity.OrderEntity;
import com.czk.gulimall.order.entity.OrderItemEntity;
import com.czk.gulimall.order.entity.PaymentInfoEntity;
import com.czk.gulimall.order.feign.CartFeignService;
import com.czk.gulimall.order.feign.MemberFeignService;
import com.czk.gulimall.order.feign.ProductFeignService;
import com.czk.gulimall.order.feign.WmsFeignService;
import com.czk.gulimall.order.interceptor.LoginUserInterceptor;
import com.czk.gulimall.order.service.OrderItemService;
import com.czk.gulimall.order.service.OrderService;
import com.czk.gulimall.order.service.PaymentInfoService;
import com.czk.gulimall.order.to.OrderCreateTo;
import com.czk.gulimall.order.vo.*;
//import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    private static ThreadLocal<OrderSubmitVo> confirmThreadLocal = new ThreadLocal();
    @Autowired
    private MemberFeignService memberFeignService;
    @Autowired
    private CartFeignService cartFeignService;
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;
    @Autowired
    private WmsFeignService wmsFeignService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private OrderItemDao orderItemDao;
    @Autowired
    private PaymentInfoService paymentInfoService;
    @Autowired
    private OrderItemService orderItemService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();
        Long id = memberResponseVo.getId();
        // 使用异步编排
        // 查收获地址列表
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            // 设置自己的上下文，原理都是存在和线程绑定的threadlocal中
            RequestContextHolder.setRequestAttributes(requestAttributes);
            // 异步时， ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            // 由于不是一个线程，导致threadLocal中取不到ServletRequestAttributes,此时会造成请求丢失情况，requestFeign会有空指针问题
            List<MemberAddressVo> address = memberFeignService.getAddress(id);
            orderConfirmVo.setAddress(address);
        }, threadPoolExecutor);
        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            // 共享之前的请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            // 购物项
            List<OrderItemVo> orderItemVos = cartFeignService.currentUserCartItems();
            orderConfirmVo.setItems(orderItemVos);
        }, threadPoolExecutor).thenRunAsync(() -> {
            // 查看是否由库存
            List<OrderItemVo> items = orderConfirmVo.getItems();
            List<Long> collect = items.stream().map(OrderItemVo::getSkuId).collect(Collectors.toList());
            List<SkuHasStockVo> skuHasStock = wmsFeignService.getSkuHasStock(collect);
            if (!skuHasStock.isEmpty()) {
                Map<Long, Boolean> map = skuHasStock.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::isHasStock));
                orderConfirmVo.setStocks(map);
            }
        }, threadPoolExecutor);

        try {
            CompletableFuture.allOf(getAddressFuture, cartFuture).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        // 积分信息
        Integer integration = memberResponseVo.getIntegration();
        orderConfirmVo.setIntegration(integration);
        // 订单总额

        // 应付总额

        // 防重复令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        // 页面存一份
        orderConfirmVo.setOrderToken(token);
        // redis服务器存一个
        stringRedisTemplate.opsForValue().set(OrderConstant.USER_TOKEN_PREFIX + memberResponseVo.getId(), token, 30, TimeUnit.MINUTES);
        return orderConfirmVo;
    }
   // @GlobalTransactional // 事务开始，全局事务
    @Override
    @Transactional
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo orderSubmitVo) {
        confirmThreadLocal.set(orderSubmitVo);
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        // 验证令牌
        String token = orderSubmitVo.getOrderToken();
        // 拿到服务器令牌
        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();
        Long id = memberResponseVo.getId();
        String redisToken = stringRedisTemplate.opsForValue().get(OrderConstant.USER_TOKEN_PREFIX + id);
        // 返回的是0和1
        // 0令牌校验失败，1校验成功
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        /**
         * lua脚本校验令牌
         * arg1 包装的lua脚本
         * arg2 key 值
         * arg3 需要对比的值
         */
        Long result = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderConstant.USER_TOKEN_PREFIX + id), token);
        if (Objects.nonNull(result) && result == 0) {
            // 成功
            OrderCreateTo orderCreateTo = createOrder();
            // 验价
            // 算出的价格
            BigDecimal payAmount = orderCreateTo.getOrder().getPayAmount();
            // 页面提交的价格
            BigDecimal payPrice = orderSubmitVo.getPayPrice();
            //
            if (Math.abs(payAmount.subtract(payPrice).intValue())<0.01){
                //
                saveOrder(orderCreateTo);
                // 锁定库存->根据订单号、所有订单项
                WareSkuLocVo lockVo=new WareSkuLocVo();
                // 订单号
                lockVo.setOrderSn(orderCreateTo.getOrder().getOrderSn());
                List<OrderItemEntity> orderItems = orderCreateTo.getOrderItems();
                List<OrderItemVo> collect = orderItems.stream().map(item -> {
                    OrderItemVo itemVo = new OrderItemVo();
                    itemVo.setSkuId(item.getSkuId());
                    itemVo.setCount(item.getSkuQuantity());
                    itemVo.setTitle(item.getSkuName());
                    return itemVo;
                }).collect(Collectors.toList());
                lockVo.setLocks(collect);
                // 为了保证高并发，库存服务可以自己回滚，可以发消息给库存服务
                // 库存服务
                R r = wmsFeignService.orderLockStock(lockVo);
                if (r.getCode()==0){
                    // 成功
                    responseVo.setCode(0);
                    // 发送订单成功消息
                    rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",orderCreateTo.getOrder());
                    return responseVo;
                }else {
                    responseVo.setCode(3);
                    return responseVo;
                }
            }
        } else {
            // 失败
            responseVo.setCode(1);
            return responseVo;
        }
    return null;

    }

    private void saveOrder(OrderCreateTo orderCreateTo) {
        OrderEntity order = orderCreateTo.getOrder();
        // 保存订单
        order.setModifyTime(new Date());
        orderDao.insert(order);
        // 保存订单项
        List<OrderItemEntity> orderItems = orderCreateTo.getOrderItems();
        orderItemService.saveBatch(orderItems);

    }

    private OrderCreateTo createOrder() {
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        // 生成订单id
        String orderId = IdWorker.getTimeId();
        // 获取邮费
        OrderSubmitVo orderSubmitVo = confirmThreadLocal.get();
        // 获取收获地址信息
        R fare = wmsFeignService.getFare(orderSubmitVo.getAddrId());
        JSONObject jsonObject = (JSONObject) fare.getData("data",new TypeReference<FareVo>() {
        });
        FareVo fareResp=jsonObject.toJavaObject(FareVo.class);
        OrderEntity order = new OrderEntity();
        order.setOrderSn(orderId);
        // 设置运费信息
        order.setFreightAmount(fareResp.getFare());
        order.setMemberId(LoginUserInterceptor.loginUser.get().getId());
        // 收货人信息
        order.setReceiverCity(fareResp.getAddress().getCity());
        order.setReceiverDetailAddress(fareResp.getAddress().getDetailAddress());
        order.setReceiverName(fareResp.getAddress().getName());
        order.setReceiverPhone(fareResp.getAddress().getPhone());
        order.setReceiverProvince(fareResp.getAddress().getProvince());
        order.setReceiverPostCode(fareResp.getAddress().getPostCode());
        order.setReceiverRegion(fareResp.getAddress().getRegion());
        // 获取订单项
        List<OrderItemEntity> orderItemEntityList = buildOrderItems(orderId);
        orderCreateTo.setOrderItems(orderItemEntityList);
        orderCreateTo.setOrder(order);
        // 验价 计算价格相关
        computePrice(order,orderItemEntityList);
        // 设置订单状态信息
        order.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        // 自动确认时间 7天
        order.setAutoConfirmDay(7);
        // 删除状态 0 未删除
        order.setDeleteStatus(0);

        return orderCreateTo;
    }

    private void computePrice(OrderEntity order, List<OrderItemEntity> orderItemEntityList) {
        BigDecimal total=new BigDecimal("0.0");
        BigDecimal coupon=new BigDecimal("0.0");
        BigDecimal integration=new BigDecimal("0.0");
        BigDecimal promotion=new BigDecimal("0.0");
        BigDecimal gift=new BigDecimal("0.0");
        BigDecimal growth=new BigDecimal("0.0");
        for (OrderItemEntity entity : orderItemEntityList) {
            BigDecimal realAmount = entity.getRealAmount();
            BigDecimal couponAmount = entity.getCouponAmount();
            coupon.add(couponAmount);
            BigDecimal integrationAmount = entity.getIntegrationAmount();
            integration.add(integrationAmount);
            BigDecimal promotionAmount = entity.getPromotionAmount();
            promotion.add(promotionAmount);
            Integer giftIntegration = entity.getGiftIntegration();
            gift.add(new BigDecimal(giftIntegration.toString()));
            Integer giftGrowth = entity.getGiftGrowth();
            growth.add(new BigDecimal(giftGrowth.toString()));
            total=total.add(realAmount);
        }
        // 设置订单价格相关
        order.setTotalAmount(total);
        // 加锁运费
        order.setPayAmount(total.add(order.getFreightAmount()));
        //
        order.setPromotionAmount(promotion);
        order.setIntegrationAmount(integration);
        order.setCouponAmount(coupon);
        // 积分
        order.setIntegration(gift.intValue());
        order.setGrowth(growth.intValue());

    }

    /**
     * 构建订单项数据
     *
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        // 获取订单项
        List<OrderItemVo> currentUserCartItems = cartFeignService.currentUserCartItems();
        //
        if (Objects.nonNull(currentUserCartItems) && currentUserCartItems.size() > 0) {
            //
            List<OrderItemEntity> collect = currentUserCartItems.stream().map(cartItem -> {
                OrderItemEntity itemEntity = buildOrderItem(cartItem);
                // 构建订单项
                itemEntity.setOrderSn(orderSn);

                return itemEntity;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    /**
     * 构建某个订单项
     *
     * @param cartItem
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        // 构建单个订单项
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        // 1 订单信息
        // 2 商品的spu
        Long skuId = cartItem.getSkuId();
        //
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        JSONObject data = (JSONObject)r.getData(new TypeReference<JSONObject>() {
        });
        SpuInfoVo spuInfoVo = data.toJavaObject(SpuInfoVo.class);
        orderItemEntity.setSpuId(spuInfoVo.getId());
        orderItemEntity.setSpuBrand(spuInfoVo.getBrandId().toString());
        orderItemEntity.setSpuName(spuInfoVo.getSpuName());
        orderItemEntity.setCategoryId(spuInfoVo.getCatalogId());
        // 3 商品的sku
        orderItemEntity.setSkuId(cartItem.getSkuId());
        orderItemEntity.setSkuName(cartItem.getTitle());
        orderItemEntity.setSkuPic(cartItem.getImage());
        orderItemEntity.setSkuPrice(cartItem.getPrice());
        // 将集合收集
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttr);
        orderItemEntity.setSkuQuantity(cartItem.getCount());

        // 4 优惠信息 ->不做
        // 5 积分信息
        orderItemEntity.setGiftGrowth(cartItem.getPrice().intValue());
        orderItemEntity.setGiftIntegration(cartItem.getPrice().intValue());
        // 订单项的价格信息
        orderItemEntity.setPromotionAmount(new BigDecimal("0"));
        orderItemEntity.setCouponAmount(new BigDecimal("0"));
        BigDecimal origin = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity()));
        BigDecimal real = origin.subtract(orderItemEntity.getCouponAmount()).subtract(orderItemEntity.getPromotionAmount());
        orderItemEntity.setRealAmount(real);
        //
        return orderItemEntity;
    }

    @Override
    public OrderEntity getorderByOrderSn(String orderSn) {
        QueryWrapper wrapper=new QueryWrapper<OrderEntity>().eq("order_sn",orderSn);
        OrderEntity one = this.getOne(wrapper);
        return one;
    }

    @Override
    public void closeOrder(OrderEntity entity) {
        // 查询1当前订单状态
        OrderEntity orderEntity = this.getById(entity.getId());
        if (orderEntity.getStatus().equals(OrderStatusEnum.CREATE_NEW.getCode())){
            // 关单
            OrderEntity update=new OrderEntity();
            update.setId(entity.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
            // 发送释放库存消息
            OrderTo orderTo=new OrderTo();
            BeanUtils.copyProperties(entity,orderTo);
            try {
                // 一、消息发送出去，由于网络波动没有发送到消息队列
                // 保证消息一定会发送出去，每一个消息要做好日志记录
                // 定期扫描数据库，将发送失败的消息再次发送
                // 二、消息发送成功，但是消息队列消息丢失，消息确认机制->手动ack
                rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",orderTo);
            }catch (Exception e) {

            }

        }
    }

    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo=new PayVo();
        //
        OrderEntity order = this.getorderByOrderSn(orderSn);

        // 总额
        BigDecimal totalAmount = order.getTotalAmount();
        // 小数点 2 位，并且向上取值
        totalAmount.setScale(2,BigDecimal.ROUND_UP);
        payVo.setTotal_amount(totalAmount.toString());
        // 交易号
        payVo.setOut_trade_no(order.getOrderSn());
        //
        List<OrderItemEntity> order_sn = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity itemEntity = order_sn.get(0);
        String skuName = itemEntity.getSkuName();
        payVo.setSubject(skuName);
        payVo.setBody(itemEntity.getSkuAttrsVals());
        return payVo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id", memberResponseVo.getId()).orderByDesc("id")
        );
        List<OrderEntity> order_sn = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(itemEntities);
            return order;
        }).collect(Collectors.toList());
        page.setRecords(order_sn);
        return new PageUtils(page);
    }

    /**
     * 处理支付宝的处理结果
     *
     * @param vo
     * @return
     */
    @Override
    public String handlePayResult(PayAsyncVo vo) throws ParseException {
        // 交易流水
        PaymentInfoEntity infoEntity=new PaymentInfoEntity();
        infoEntity.setAlipayTradeNo(vo.getTrade_no());
        //
        infoEntity.setPaymentStatus(vo.getTrade_status());
        //
        infoEntity.setOrderSn(vo.getOut_trade_no());
        infoEntity.setCallbackTime(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(vo.getNotify_time()));
        paymentInfoService.save(infoEntity);
        // 修改订单状态信息
        if (vo.getTrade_status().equals("TRADE_SUCCESS")||vo.getTrade_status().equals("TRADE_FAILURE")){
            // 支付成功
            String out_trade_no = vo.getOut_trade_no();
            this.updateOrderStatus(out_trade_no,OrderStatusEnum.PAYED.getCode());
        }
        return null;
    }

    private void updateOrderStatus(String out_trade_no, Integer code) {
        this.baseMapper.updateOrderStatus(out_trade_no,code);
    }
}